package cn.com.cnxfs.relaxchat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

public class ListFragment extends Fragment {
    private Context context;
    public static List<Friend> friends = new ArrayList<>();
    private MyDatabaseHelper databaseHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = getActivity();
        databaseHelper = new MyDatabaseHelper(context, "database.db", null, 1); //打开本地数据库
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        SharedPreferences preferences = Objects.requireNonNull(getActivity()).getSharedPreferences("db_login",MODE_PRIVATE);
        final String id = preferences.getString("id","0"); //获取当前用户的id
        final Adapter_friend adapter = new Adapter_friend(context, R.layout.layout_friend, friends);
        ListView listView = getActivity().findViewById(R.id.list_friend);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(context, ChatActivity.class);
                intent.putExtra("id",friends.get(position).getId());
                intent.putExtra("uid",friends.get(position).getUid()); //登录的用户自己id
                intent.putExtra("friend",friends.get(position).getFriend()); //好友的id
                intent.putExtra("username",friends.get(position).getUsername());
                intent.putExtra("nickname",friends.get(position).getNickname());
                intent.putExtra("state",friends.get(position).getState()); //消息是否已读，0未读1已读
                startActivity(intent); //跳转到聊天页面
            }
        });
        //下面开始从后端获取好友列表数据
        final Runnable fresh_runnable = new Runnable() {
            @Override
            public void run() { //向后端发送请求
                SQLiteDatabase db = databaseHelper.getWritableDatabase();
                try {
                    FormBody.Builder params = new FormBody.Builder();
                    assert id != null;
                    params.add("uid",id); //添加url参数
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(Api.url[0]+"/friend/list").post(params.build())
                            .build();
                    Response response = client.newCall(request).execute(); //执行发送指令
                    String responseData = response.body().string();
                    Log.d("获取到的好友",responseData);
                    try{ //下面解析后端传回的JSON数组
                        friends.clear(); //清空容器
                        JSONArray jsonArray = new JSONArray(responseData);
                        db.delete("friend","",null); //把friend表清空，再重新添加最新数据
                        ContentValues values = new ContentValues(); //要添加到数据库中的数据
                        for(int i = 0; i<jsonArray.length(); i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            Friend friend = new Friend();
                            friend.setId(Integer.parseInt(jsonObject.getString("id"))); //服务器数据库中这一行的id
                            friend.setUid(Integer.parseInt(id));  //我自己的ID
                            friend.setFriend(Integer.parseInt(jsonObject.getString("friend"))); //好友的ID
                            friend.setState((byte)1); //消息是否已读，主动刷新好友的情况下默认已读
                            friend.setNickname(jsonObject.getString("nickname"));
                            friend.setUsername(jsonObject.getString("username"));
                            friends.add(friend);
                            values.put("id", Integer.parseInt(jsonObject.getString("id")));//服务器数据库中这一行的id
                            values.put("friend",friend.getFriend()); //好友的ID，特别注意，根据上面已经判断后的结果获取
                            values.put("nickname",jsonObject.getString("nickname"));
                            values.put("state", 1); //消息是否已读，主动刷新好友的情况下默认已读
                            db.insert("friend", null, values);
                            values.clear();
                        }
                        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(),"好友列表刷新成功！",Toast.LENGTH_SHORT).show();
                                adapter.notifyDataSetChanged();  //刷新ListView
                            }
                        });
                    }catch (Exception e){
                        e.printStackTrace();
                        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(),"服务器传来的好友信息有错！",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(),"好友列表获取失败！",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        };
        Button button_fresh = getActivity().findViewById(R.id.button_fresh_friendlist);
        button_fresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(fresh_runnable).start();
            }
        }); //刷新按钮
        friends.clear();
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        Cursor cursor = db.query("friend",null,"",null,null,null,"nickname");
        if(cursor.moveToFirst()){
            do{  //从本地数据库里读出数据
                Friend friend = new Friend();
                friend.setId(cursor.getInt(cursor.getColumnIndex("id")));
                friend.setNickname(cursor.getString(cursor.getColumnIndex("nickname")));
                assert id != null;
                friend.setUid(Integer.parseInt(id)); //当前登录用户的id
                friend.setFriend(cursor.getInt(cursor.getColumnIndex("friend"))); //好友的id
                friend.setState((byte)cursor.getInt(cursor.getColumnIndex("state"))); //已读状态
                friends.add(friend);
            }while(cursor.moveToNext());
            adapter.notifyDataSetChanged();
            Log.d("List页面","从本地数据库读取旧好友列表！");
        }else //如果数据库为空，则联网获取一下新列表
            new Thread(fresh_runnable).start();
        cursor.close();

        final SearchView searchView = getActivity().findViewById(R.id.searchbar);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(final String query) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{  //根据用户名查找用户
                            FormBody.Builder params = new FormBody.Builder();
                            params.add("username",query); //添加url参数
                            OkHttpClient client = new OkHttpClient();
                            Request request = new Request.Builder()
                                    .url(Api.url[0]+"/login/search").post(params.build())
                                    .build();
                            Response response = client.newCall(request).execute(); //执行发送指令
                            String responseData = response.body().string();
                            if(responseData.equals("")){ //没有找到该用户
                                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                        builder.setTitle("添加新好友");
                                        builder.setMessage("对不起，用户"+query+"不存在！");
                                        builder.setCancelable(false);
                                        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        });
                                        builder.show();
                                    }
                                });
                            }else{
                                final JSONObject jsonObject = new JSONObject(responseData);
                                final int friendUid = jsonObject.getInt("id");
                                final AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                builder.setTitle("添加新好友");
                                builder.setMessage("确认要添加\""+jsonObject.getString("nickname")+"\"为好友吗？");
                                builder.setCancelable(false);
                                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                });
                                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //先判断是不是已经成为好友了，防止重复添加好友
                                        boolean flag = false;
                                        for(Friend friend: friends){
                                            if(friend.getFriend() == friendUid) {
                                                flag = true;
                                                break;
                                            }
                                        }
                                        if(flag){
                                            Toast.makeText(context,"对方已是您的好友！无需重复添加！",Toast.LENGTH_SHORT).show();
                                        }else{
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {  //向后端传递好友请求
                                                    try{
                                                        FormBody.Builder params = new FormBody.Builder();
                                                        assert id != null;
                                                        params.add("uid",id); //添加url参数
                                                        params.add("friend",jsonObject.getString("id"));
                                                        OkHttpClient client = new OkHttpClient();
                                                        Request request = new Request.Builder()
                                                                .url(Api.url[0]+"/friend/add").post(params.build())
                                                                .build();
                                                        Response response = client.newCall(request).execute(); //执行发送指令
                                                        new Thread(fresh_runnable).start(); //刷新好友列表
                                                        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                Toast.makeText(context,"好友添加成功！",Toast.LENGTH_SHORT).show();
                                                                searchView.setQuery("",false);
                                                            }
                                                        });
                                                    }catch (Exception e){
                                                        e.printStackTrace();
                                                        Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                Toast.makeText(context,"好友请求发送失败！请检查网络连接！",Toast.LENGTH_SHORT).show();
                                                            }
                                                        });
                                                    }
                                                }
                                            }).start();
                                        }
                                    }
                                });
                                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        builder.show();
                                    }
                                });
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(context,"请检查网络连接！",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }
}

class Adapter_friend extends ArrayAdapter<Friend>{
    private int layoutId;
    private Context mContext;

    Adapter_friend(Context context, int layoutId, List<Friend> list){
        super(context, layoutId, list);
        this.layoutId = layoutId;
        this.mContext = context;
    }
    @NonNull
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final Friend item = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(layoutId, parent, false);
        TextView textView = view.findViewById(R.id.friend_nickname);
        Button button = view.findViewById(R.id.button_del_friend);

        assert item != null;
        textView.setText(item.getNickname());
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(item.getId()==0){  //好友列表里的数据可能来自陌生人发消息而新增的，此情况下不存在id
                    ((Activity)mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(),"请先刷新好友列表！",Toast.LENGTH_SHORT).show();
                        }
                    });
                }else{
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                    builder.setTitle("删除好友");
                    builder.setMessage("确认要删除好友\""+item.getNickname()+"\"?");
                    builder.setCancelable(false);
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() { //向后端发送请求
                                    try {
                                        FormBody.Builder params = new FormBody.Builder();
                                        params.add("id",item.getId()+""); //添加url参数
                                        OkHttpClient client = new OkHttpClient();
                                        Request request = new Request.Builder()
                                                .url(Api.url[0]+"/friend/deny").post(params.build())
                                                .build();
                                        Response response = client.newCall(request).execute(); //执行发送指令
                                        ((Activity)mContext).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(getContext(),"好友已被删除！",Toast.LENGTH_SHORT).show();
                                                ListFragment.friends.remove(position);
                                                notifyDataSetChanged(); //从好友数组中删除，通知ListView刷新显示的好友列表
                                            }
                                        });
                                    }catch (Exception e){
                                        e.printStackTrace();
                                        ((Activity)mContext).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(getContext(),"好友删除失败！",Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }
                                }
                            }).start();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    builder.show();
                }
            }
        });
        return view;
    }
}
